<template>
  <div v-loading="loading">
    <page-header />
    <div class="pay-container">
      <div>
        <h2><i class="back-icon el-icon-back" @click="goBack" /> 返回购物车</h2>
      </div>
      <div class="choose-address-div">
        <!-- <el-radio-group v-for="(item,index) in userAddressList" :key="index" v-model="selectAdd"> -->
        <div class="title">选择收货地址</div>
        <hr>
        <!-- <el-divider /> -->
        <div v-if="userAddressList && userAddressList.length > 0" class="content">
          <el-row
            v-for="(item, index) in userAddressList"
            :key="index"
            v-model="selectAdd"
          >
            <el-col :span="24" class="add-col">
              <el-radio v-model="selectAdd" :label="item.id">
                <span>{{
                  item.province + item.city + item.town + " " + item.detail
                }}</span>
                <span>{{
                  " (" + item.username + "" + "收)" + " " + item.phone
                }}</span>
                <span v-if="item.isDefault">(默认)</span>
              </el-radio>
            </el-col>
          </el-row>
        </div>
        <div v-else class="content">暂无！ <el-button type="primary" @click="toAddAddress">添加</el-button></div>
        <!-- </el-radio-group> -->
      </div>
      <el-divider />
      <div class="order-list">
        <div class="title">确认订单信息</div>
        <hr>
        <el-table :data="buyUserCart" style="width: 100%">
          <el-table-column label="商品信息" prop="id">
            <template slot-scope="scope">
              <div class="book-img-des-container">
                <div class="book-img">
                  <el-image
                    style="width: 100%; height: 100%"
                    :src="scope.row.book.bookImgs.length > 0?scope.row.book.bookImgs[0].imgName:''"
                    fit="contain"
                  />
                  <!-- scope.row.book.bookImgs.length > 0?scope.row.book.bookImgs[0].imgName:'' -->
                  <!-- scope.row.book.bookImgs[0].imgName -->
                </div>
                <div class="book-des">
                  <div class="book-name">
                    <!-- scope.row.book.bookName -->
                    <span>{{ scope.row.book.bookName }}</span>
                  </div>
                  <div class="book-author">
                    <span>{{ scope.row.book.author }}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="book.price" />
          <el-table-column label="数量" prop="num" />
          <el-table-column label="总金额" prop="totalMoney">
            <template slot-scope="scope">
              <span>{{
                (scope.row.book.price * scope.row.num) | num2Point
              }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="confirm-div">
          <div class="container">
            <div>合计：{{ buyCount }}</div>
            <div>总金额：￥{{ totalMoney | num2Point }}</div>
            <div>
              <el-button
                type="primary"
                @click="submitOrder"
              >提交订单</el-button>
            </div>
          </div>
        </div>
      </div>
      <right-bottom-fixd />
    </div>

    <el-dialog
      title="支付"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>是否确认支付</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelPay">取 消</el-button>
        <el-button type="primary" @click="doPay">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import RightBottomFixd from '@/components/RightBottomFixd'
import PageHeader from '@/components/PageHeader'
import { addOrders, payOrders } from '@/api/order'
import { delCartByIds } from '@/api/cart'
import { getUserInfoAndAddress } from '@/common/common'
export default {
  components: {
    RightBottomFixd,
    PageHeader
  },
  data() {
    return {
      // buyGoodList: [],
      // 选择的收获地址的id
      selectAdd: '',
      loading: false,
      dialogVisible: false,
      // 下单成功保存的订单列表
      orders: [],
      buyUserCart: ''
    }
  },
  computed: {
    // 总金额
    totalMoney() {
      let money = 0
      if (this.buyUserCart) {
        this.buyUserCart.forEach(element => {
          money += element.book.price * element.num
        })
      }
      return money
    },
    buyCount() {
      return this.buyUserCart ? this.buyUserCart.length : 0
    },
    userDetail() {
      return this.$store.getters.userDetail
    },
    // 用户收获地址
    userAddressList() {
      return this.$store.getters.userAddressList
    }
  },
  created() {
    getUserInfoAndAddress().then(res => {
      this.setDefaultSelectAdd()
    })
    this.getLocalStageBuyCart()
  },
  destroyed() {
    localStorage.removeItem('buyUserCart')
  },
  methods: {
    toAddAddress() {
      this.$router.push('profile/4')
    },
    getLocalStageBuyCart() {
      this.buyUserCart = JSON.parse(localStorage.getItem('buyUserCart'))
      // console.log(this.buyUserCart)
    },
    goBack() {
      this.$router.push('/profile/2')
    },
    // 提交订单
    submitOrder() {
      // 构造多个订单对象，
      if (!this.buyUserCart || this.buyUserCart.length === 0) {
        this.$message.error('opos！当前页面似乎出错了')
        setTimeout(() => {
          this.$router.push('/profile/2')
        }, 1500)
        return
      }
      if (!this.userAddressList || this.userAddressList.length === 0) {
        this.$message.error('请先添加收货地址！')
        setTimeout(() => {
          this.$router.push('/profile/4')
        }, 1500)
        return
      }
      const orderArr = []
      this.buyUserCart.forEach(element => {
        const order = {
          price: element.book.price,
          num: element.num,
          fkBookId: element.bookId,
          orderAdd: this.selectAdd
        }
        orderArr.push(order)
      })
      // 执行提交订单
      const payload = {
        uid: this.userDetail.id,
        orderArr
      }
      this.doOrder(payload)
    },
    doOrder(payload) {
      // 下单成功后页面不能操作
      this.loading = true
      addOrders(payload).then(res => {
        // 下单成功,loading = false,弹出支付窗口
        setTimeout(() => {
          this.loading = false
          this.orders = res.object
          // 展示支付窗口
          this.dialogVisible = true
        }, 1000)
        // 下单成功后，把原来的购物车的数据删掉
        this.deleteCart()
      }).catch(() => {
        // 下单失败，loading = false,返回购物车
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '下单失败'
        })
        // 重定向到购物车
        setTimeout(() => {
          this.$router.push('/profile/2')
        }, 2000)
      })
    },
    deleteCart() {
      const arr = []
      this.buyUserCart.forEach(element => {
        arr.push(element.id)
      })
      const idsObj = {
        ids: arr
      }
      delCartByIds(idsObj).then(res => {
        this.$store.dispatch('cart/getCarts', this.userDetail.id)
      })
    },
    // 取消支付
    cancelPay() {
      this.$confirm('确认关闭？')
        .then(_ => {
          // done()
          // 重定向到购物车
          setTimeout(() => {
            this.$router.push('/profile/3')
          }, 1500)
        })
        .catch(_ => { })
    },
    // 确定支付
    doPay() {
      // 更改订单状太为成功支付
      const payOrderList = []
      this.orders.forEach(element => {
        const order = {
          id: element.id,
          status: 1
        }
        payOrderList.push(order)
      })
      payOrders(payOrderList).then(res => {
        // 支付成功
        this.$notify({
          title: '成功',
          message: '成功支付',
          type: 'success'
        })
      }).catch(() => {
        // 支付失败
        this.$notify.error({
          title: '错误',
          message: '支付失败'
        })
      })
      // 跳转订单页面
      setTimeout(() => {
        this.$router.push('/profile/3')
      }, 1000)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          // 重定向到购物车
          setTimeout(() => {
            this.$router.push('/profile/3')
          }, 1500)
        })
        .catch(_ => { })
    },
    // 设置选中默认收货地址
    setDefaultSelectAdd() {
      this.userAddressList.forEach(element => {
        if (element.isDefault) {
          this.selectAdd = element.id
        }
      })
    }
  }

}
</script>
<style lang="scss" scoped>
.back-icon:hover {
  color: #007acc;
}
.pay-container {
  margin-top: 40px;
  margin-left: 200px;
  margin-right: 200px;
  // background-color: pink;
}
.choose-address-div {
  widows: 100%;
  margin: 0 20px;
  .title {
    font-weight: 700;
  }

  .content {
    margin-left: 20px;
    .add-col {
      margin-bottom: 10px;
    }
    span {
      font-size: 16px;
    }
  }
}

.book-img-des-container {
  display: flex;
  .book-img {
    width: 80px;
    height: 80px;
  }
  .book-des {
    margin-left: 20px;
    display: flex;
    flex-direction: column;
  }
}
.order-list {
  margin: 0 20px;
  .title {
    font-weight: 700;
  }
}

.confirm-div {
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
  .container {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    div {
      margin-bottom: 5px;
      color: #ff5000;
    }
  }
}
</style>
